package com.knife.message.domain.service.impl;

import com.knife.message.domain.service.KnifeEmailSendHelper;
import com.knife.message.infra.exception.SendFailedException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

/**
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @date 2022年06月12日 星期日 8:49 下午
 * @description
 * @since 1.0
 */
@Component
public class DefaultKnifeEmailSendHelper implements KnifeEmailSendHelper {
    @Autowired
    private JavaMailSender mailSender;

    @Value(value = "${spring.mail.username}")
    private String sendEmailAddress;

    @Override
    public void sendEmail(String subject, String content, List<String> emailList) throws SendFailedException, MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(content,true);
        mimeMessageHelper.setTo(emailList.toArray(new String[0]));
        mimeMessageHelper.setFrom("记账系统(knife-keep-account)");
        mailSender.send(mimeMessage);
    }

    @Override
    public void sendEmail(String subject, String content, String email) throws SendFailedException,MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(content,true);
        mimeMessageHelper.setTo(email);
        mimeMessageHelper.setFrom("记账系统(knife-keep-account)<"+sendEmailAddress+">");
        mailSender.send(mimeMessage);
    }

    @Override
    public void sendEmailWithAttachment(String subject, String content, String email, List<File> fileList) throws SendFailedException, MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(content,true);
        mimeMessageHelper.setTo(email);
        mimeMessageHelper.setFrom("记账系统(knife-keep-account)<"+sendEmailAddress+">");
        if (CollectionUtils.isNotEmpty(fileList)){
            for (File file : fileList) {
                mimeMessageHelper.addAttachment(file.getName(),file);
            }
        }
        mailSender.send(mimeMessage);
    }
}
